package utils

import (
	"regexp"

	"golang.aliyun-inc.com/agit/agit/proc-receive-hook/protocol"
	satellite "golang.aliyun-inc.com/agit/satellite-proto/go"
)

// CheckOID check if OID is valid
func CheckOID(oid string) bool {
	if len(oid) < 6 || len(oid) > 40 {
		return false
	}
	match, _ := regexp.MatchString(string("[0-9a-z]+"), oid)
	return match
}

func PrepareCommandsSuccess(commands []*protocol.Command, pbcmd *satellite.Command, hint string) error {
	for i, command := range commands {
		if i == 0 {
			command.SetHint(hint)
		}
		intended := protocol.GitCommand{
			OldOID: command.OldOID,
			NewOID: pbcmd.GetNewOid(),
			Ref:    string(pbcmd.Refname),
		}
		err := command.SetIntendedCommand(intended)
		if err != nil {
			return err
		}
	}
	return nil
}

func SetCommandsNGReason(commands []*protocol.Command, reason string) {
	for _, command := range commands {
		command.SetStatusNG(reason)
	}
}

func SetCommandsHint(commands []*protocol.Command, hint string) {
	if len(commands) == 0 {
		return
	}
	commands[0].SetHint(hint)
}
